using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ShaHashChecker
{
    public static class HashHelper
    {
        public static bool CheckHash(string hashString, string filePath)
        {
            try
            {

                var hashListFile = filePath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SHA1_list.txt");
                if (!File.Exists(hashListFile))
                {
                    Console.WriteLine("\nFile {0} not found. Please make sure you have the right file, in the right location", hashListFile);
                    throw new FileNotFoundException();
                }
                Console.WriteLine("\nSearching {0}", hashListFile);
                Console.Write("Searching for hash.   0%");
                var lineCounter = 0;
                var linesPercent = 0;

                using (var textStreamReader = new StreamReader(hashListFile))
                {
                    while (textStreamReader.Peek() > 0)
                    {
                        if (textStreamReader.ReadLine() == hashString)
                        {
                            Console.WriteLine("\n");
                            return true;
                        }
                        lineCounter++;

                        if (100 * lineCounter / 6400000 <= linesPercent) continue;

                        linesPercent++;
                        Console.Write("\b\b\b\b{0,3}%", linesPercent);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nError while checking hash list!");
                throw;
            }
            Console.WriteLine("\n");
            return false;
        }

        public static int GetPad(string[] args)
        {
            int pad;
            if ((args.Length > 1) && (Int32.TryParse(args[1].Split(':')[1], out pad)))
                return pad;
            return 0;
        }

        public static string GetHashString(string source)
        {
            var enc = Encoding.ASCII;
            var sha = new SHA1CryptoServiceProvider();
            var hash = sha.ComputeHash(enc.GetBytes(source));
            var hashString = BitConverter.ToString(hash).Replace("-", String.Empty);
            return hashString;
        }
    }
}